<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      go/2-Go语言基础/19-接口（二） | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>go/2-Go语言基础/19-接口（二）</h2>



  <p class="post-date">2019-02-10</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><hr>
<p>title: “19-接口（二）”<br>date: 2019-03-10 08:08<br>tags:</p>
<ul>
<li>Go</li>
</ul>
<hr>
<h3 id="实现接口：指针接受者与值接受者"><a href="#实现接口：指针接受者与值接受者" class="headerlink" title="实现接口：指针接受者与值接受者"></a>实现接口：指针接受者与值接受者</h3><p>在接口（一）上的所有示例中，我们都是使用值接受者（Value Receiver）来实现接口的。我们同样可以使用指针接受者（Pointer Receiver）来实现接口。只不过在用指针接受者实现接口时，还有一些细节需要注意。我们通过下面的代码来理解吧。 </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Describer <span class="keyword">interface</span> &#123;  </span><br><span class="line">    Describe()</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span> &#123;  </span><br><span class="line">    name <span class="keyword">string</span></span><br><span class="line">    age  <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p Person)</span> <span class="title">Describe</span><span class="params">()</span></span> &#123; <span class="comment">// 使用值接受者实现  </span></span><br><span class="line">    fmt.Printf(<span class="string">"%s is %d years old\n"</span>, p.name, p.age)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Address <span class="keyword">struct</span> &#123;</span><br><span class="line">    state   <span class="keyword">string</span></span><br><span class="line">    country <span class="keyword">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(a *Address)</span> <span class="title">Describe</span><span class="params">()</span></span> &#123; <span class="comment">// 使用指针接受者实现</span></span><br><span class="line">    fmt.Printf(<span class="string">"State %s Country %s"</span>, a.state, a.country)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    <span class="keyword">var</span> d1 Describer</span><br><span class="line">    p1 := Person&#123;<span class="string">"Sam"</span>, <span class="number">25</span>&#125;</span><br><span class="line">    d1 = p1</span><br><span class="line">    d1.Describe()</span><br><span class="line">    p2 := Person&#123;<span class="string">"James"</span>, <span class="number">32</span>&#125;</span><br><span class="line">    d1 = &amp;p2</span><br><span class="line">    d1.Describe()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> d2 Describer</span><br><span class="line">    a := Address&#123;<span class="string">"Washington"</span>, <span class="string">"USA"</span>&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 如果下面一行取消注释会导致编译错误：</span></span><br><span class="line"><span class="comment">       cannot use a (type Address) as type Describer</span></span><br><span class="line"><span class="comment">       in assignment: Address does not implement</span></span><br><span class="line"><span class="comment">       Describer (Describe method has pointer</span></span><br><span class="line"><span class="comment">       receiver)</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="comment">//d2 = a</span></span><br><span class="line"></span><br><span class="line">    d2 = &amp;a <span class="comment">// 这是合法的</span></span><br><span class="line">    <span class="comment">// 因为在第 22 行，Address 类型的指针实现了 Describer 接口</span></span><br><span class="line">    d2.Describe()</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面程序中的第 13 行，结构体 <code>Person</code> 使用值接受者，实现了 <code>Describer</code> 接口。  </p>
<p>我们在讨论方法的时候就已经提到过，使用值接受者声明的方法，既可以用值来调用，也能用指针调用。<strong>不管是一个值，还是一个可以解引用的指针，调用这样的方法都是合法的</strong>。</p>
<p><code>p1</code> 的类型是 <code>Person</code>，在第 29 行，<code>p1</code> 赋值给了 <code>d1</code>。由于 <code>Person</code> 实现了接口变量 <code>d1</code>，因此在第 30 行，会打印 <code>Sam is 25 years old</code>。</p>
<p>接下来在第 32 行，<code>d1</code> 又赋值为 <code>&amp;p2</code>，在第 33 行同样打印输出了 <code>James is 32 years old</code>。棒棒哒。:) </p>
<p>在 22 行，结构体 <code>Address</code> 使用指针接受者实现了 <code>Describer</code> 接口。 </p>
<p>在上面程序里，如果去掉第 45 行的注释，我们会得到编译错误：<code>main.go:42: cannot use a (type  Address) as type Describer in assignment: Address does not implement  Describer (Describe method has pointer receiver)</code>。这是因为在第 22 行，我们使用 <code>Address</code> 类型的指针接受者实现了接口 <code>Describer</code>，而接下来我们试图用 <code>a</code> 来赋值 <code>d2</code>。然而 <code>a</code> 属于值类型，它并没有实现 <code>Describer</code> 接口。你应该会很惊讶，因为我们曾经学习过，使用指针接受者的方法，无论指针还是值都可以调用它。那么为什么第 45 行的代码就不管用呢？</p>
<p><strong>其原因是：对于使用指针接受者的方法，用一个指针或者一个可取得地址的值来调用都是合法的。但接口中存储的具体值（Concrete Value）并不能取到地址，因此在第 45 行，对于编译器无法自动获取 a 的地址，于是程序报错</strong>。  </p>
<p>第 47 行就可以成功运行，因为我们将 <code>a</code> 的地址 <code>&amp;a</code> 赋值给了 <code>d2</code>。  </p>
<p>程序的其他部分不言而喻。该程序会打印：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Sam is 25 years old  </span><br><span class="line">James is 32 years old  </span><br><span class="line">State Washington Country USA</span><br></pre></td></tr></table></figure>

<h3 id="实现多个接口"><a href="#实现多个接口" class="headerlink" title="实现多个接口"></a>实现多个接口</h3><p>类型可以实现多个接口。我们看看下面程序是如何做到的。  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> SalaryCalculator <span class="keyword">interface</span> &#123;  </span><br><span class="line">    DisplaySalary()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> LeaveCalculator <span class="keyword">interface</span> &#123;  </span><br><span class="line">    CalculateLeavesLeft() <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Employee <span class="keyword">struct</span> &#123;  </span><br><span class="line">    firstName <span class="keyword">string</span></span><br><span class="line">    lastName <span class="keyword">string</span></span><br><span class="line">    basicPay <span class="keyword">int</span></span><br><span class="line">    pf <span class="keyword">int</span></span><br><span class="line">    totalLeaves <span class="keyword">int</span></span><br><span class="line">    leavesTaken <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e Employee)</span> <span class="title">DisplaySalary</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    fmt.Printf(<span class="string">"%s %s has salary $%d"</span>, e.firstName, e.lastName, (e.basicPay + e.pf))</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e Employee)</span> <span class="title">CalculateLeavesLeft</span><span class="params">()</span> <span class="title">int</span></span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> e.totalLeaves - e.leavesTaken</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    e := Employee &#123;</span><br><span class="line">        firstName: <span class="string">"Naveen"</span>,</span><br><span class="line">        lastName: <span class="string">"Ramanathan"</span>,</span><br><span class="line">        basicPay: <span class="number">5000</span>,</span><br><span class="line">        pf: <span class="number">200</span>,</span><br><span class="line">        totalLeaves: <span class="number">30</span>,</span><br><span class="line">        leavesTaken: <span class="number">5</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> s SalaryCalculator = e</span><br><span class="line">    s.DisplaySalary()</span><br><span class="line">    <span class="keyword">var</span> l LeaveCalculator = e</span><br><span class="line">    fmt.Println(<span class="string">"\nLeaves left ="</span>, l.CalculateLeavesLeft())</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上述程序在第 7 行和第 11 行分别声明了两个接口：<code>SalaryCalculator</code> 和 <code>LeaveCalculator</code>。  </p>
<p>第 15 行定义了结构体 <code>Employee</code>，它在第 24 行实现了 <code>SalaryCalculator</code> 接口的 <code>DisplaySalary</code> 方法，接着在第 28 行又实现了 <code>LeaveCalculator</code> 接口里的 <code>CalculateLeavesLeft</code> 方法。于是 <code>Employee</code> 就实现了 <code>SalaryCalculator</code> 和 <code>LeaveCalculator</code> 两个接口。  </p>
<p>第 41 行，我们把 <code>e</code> 赋值给了 <code>SalaryCalculator</code> 类型的接口变量 ，而在 43 行，我们同样把 <code>e</code> 赋值给 <code>LeaveCalculator</code> 类型的接口变量 。由于 <code>e</code> 的类型 <code>Employee</code> 实现了 <code>SalaryCalculator</code> 和 <code>LeaveCalculator</code> 两个接口，因此这是合法的。  </p>
<p>该程序会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Naveen Ramanathan has salary $5200  </span><br><span class="line">Leaves left &#x3D; 25</span><br></pre></td></tr></table></figure>

<h3 id="接口的嵌套"><a href="#接口的嵌套" class="headerlink" title="接口的嵌套"></a>接口的嵌套</h3><p>尽管 Go 语言没有提供继承机制，但可以通过嵌套其他的接口，创建一个新接口。  </p>
<p>我们来看看这如何实现。  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> SalaryCalculator <span class="keyword">interface</span> &#123;  </span><br><span class="line">    DisplaySalary()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> LeaveCalculator <span class="keyword">interface</span> &#123;  </span><br><span class="line">    CalculateLeavesLeft() <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> EmployeeOperations <span class="keyword">interface</span> &#123;  </span><br><span class="line">    SalaryCalculator</span><br><span class="line">    LeaveCalculator</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Employee <span class="keyword">struct</span> &#123;  </span><br><span class="line">    firstName <span class="keyword">string</span></span><br><span class="line">    lastName <span class="keyword">string</span></span><br><span class="line">    basicPay <span class="keyword">int</span></span><br><span class="line">    pf <span class="keyword">int</span></span><br><span class="line">    totalLeaves <span class="keyword">int</span></span><br><span class="line">    leavesTaken <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e Employee)</span> <span class="title">DisplaySalary</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    fmt.Printf(<span class="string">"%s %s has salary $%d"</span>, e.firstName, e.lastName, (e.basicPay + e.pf))</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e Employee)</span> <span class="title">CalculateLeavesLeft</span><span class="params">()</span> <span class="title">int</span></span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> e.totalLeaves - e.leavesTaken</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    e := Employee &#123;</span><br><span class="line">        firstName: <span class="string">"Naveen"</span>,</span><br><span class="line">        lastName: <span class="string">"Ramanathan"</span>,</span><br><span class="line">        basicPay: <span class="number">5000</span>,</span><br><span class="line">        pf: <span class="number">200</span>,</span><br><span class="line">        totalLeaves: <span class="number">30</span>,</span><br><span class="line">        leavesTaken: <span class="number">5</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> empOp EmployeeOperations = e</span><br><span class="line">    empOp.DisplaySalary()</span><br><span class="line">    fmt.Println(<span class="string">"\nLeaves left ="</span>, empOp.CalculateLeavesLeft())</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上述程序的第 15 行，我们创建了一个新的接口 <code>EmployeeOperations</code>，它嵌套了两个接口：<code>SalaryCalculator</code> 和 <code>LeaveCalculator</code>。</p>
<p>如果一个类型定义了 <code>SalaryCalculator</code> 和 <code>LeaveCalculator</code> 接口里包含的方法，我们就称该类型实现了 <code>EmployeeOperations</code> 接口。</p>
<p>在第 29 行和第 33 行，由于 <code>Employee</code> 结构体定义了 <code>DisplaySalary</code> 和 <code>CalculateLeavesLeft</code> 方法，因此它实现了接口 <code>EmployeeOperations</code>。</p>
<p>在 46 行，<code>empOp</code> 的类型是 <code>EmployeeOperations</code>，<code>e</code> 的类型是 <code>Employee</code>，我们把 <code>empOp</code> 赋值为 <code>e</code>。接下来的两行，<code>empOp</code> 调用了 <code>DisplaySalary()</code> 和 <code>CalculateLeavesLeft()</code> 方法。</p>
<p>该程序输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Naveen Ramanathan has salary $5200</span><br><span class="line">Leaves left &#x3D; 25</span><br></pre></td></tr></table></figure>

<h3 id="接口的零值"><a href="#接口的零值" class="headerlink" title="接口的零值"></a>接口的零值</h3><p>接口的零值是 <code>nil</code>。对于值为 <code>nil</code> 的接口，其底层值（Underlying Value）和具体类型（Concrete Type）都为 <code>nil</code>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Describer <span class="keyword">interface</span> &#123;  </span><br><span class="line">    Describe()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    <span class="keyword">var</span> d1 Describer</span><br><span class="line">    <span class="keyword">if</span> d1 == <span class="literal">nil</span> &#123;</span><br><span class="line">        fmt.Printf(<span class="string">"d1 is nil and has type %T value %v\n"</span>, d1, d1)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面程序里的 <code>d1</code> 等于 <code>nil</code>，程序会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">d1 is nil and has type &lt;nil&gt; value &lt;nil&gt;</span><br></pre></td></tr></table></figure>

<p>对于值为 <code>nil</code> 的接口，由于没有底层值和具体类型，当我们试图调用它的方法时，程序会产生 <code>panic</code> 异常。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Describer <span class="keyword">interface</span> &#123;</span><br><span class="line">    Describe()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    <span class="keyword">var</span> d1 Describer</span><br><span class="line">    d1.Describe()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上述程序中，<code>d1</code> 等于 <code>nil</code>，程序产生运行时错误 <code>panic</code>： <strong>panic: runtime error: invalid memory address or nil pointer dereference  [signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0xc8527]</strong> 。  </p>
</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/go/2-Go%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80/18-%E6%8E%A5%E5%8F%A3%EF%BC%88%E4%B8%80%EF%BC%89/">
        <span class="nav-arrow">← </span>
        
          go/2-Go语言基础/18-接口（一）
        
      </a>
    
    
      <a class="nav-right" href="/go/2-Go%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80/24-Select/">
        
          go/2-Go语言基础/24-Select
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#实现接口：指针接受者与值接受者"><span class="toc-nav-text">实现接口：指针接受者与值接受者</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#实现多个接口"><span class="toc-nav-text">实现多个接口</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#接口的嵌套"><span class="toc-nav-text">接口的嵌套</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#接口的零值"><span class="toc-nav-text">接口的零值</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/go/2-Go语言基础/19-接口（二）/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "go/2-Go语言基础/19-接口（二）",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>